<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\libs\curl;
use app\libs\common;
use app\libs\helper;
use yii\db\Query;

class MenuController extends Controller {

    public $enableCsrfValidation = false;

    public function actionGetmenu() {

        $sql = "SELECT type,name,`key` FROM cate WHERE pid=0";
        $res = Yii::$app->db->createCommand($sql)->queryAll();

        //从数据库里查的数据处理成微信菜单需要的数据格式
        //
        //
        //
        $temp = [];
        foreach ($res as $key => $val) {
            //公众 部分
            $temp[$key]['type'] = $val['type'];
            $temp[$key]['name'] = $val['name'];

            //
            if ($val['type'] == 'view') {
                $temp[$key]['url'] = $val['key'];
            } else if ($val['type'] == 'click') {
                $temp[$key]['key'] = $val['key'];
            }
        }
        $menu['button'] = $temp;
//        print_r($menu);
//        exit;
//        $menu['button'] = [
//                [
//                'type' => 'click',
//                'name' => 'PHP1606c',
//                'key' => 'abc',
//            ],
//                [
//               
//                'name' => '菜单手册',
//                'sub_button' => [
//                   [
//                'type' => 'click',
//                'name' => 'PHP1606c',
//                'key' => 'abc',
//            ],
//             [
//                'type' => 'click',
//                'name' => 'PHP1606c',
//                'key' => 'abc',
//            ],
//                ]
//            ],
//        ];
        $token = $this->_savetoken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;

        $res = Curl::_post($url, json_encode($menu, JSON_UNESCAPED_UNICODE));
        print_r($res);
        exit;
    }

    public function actionIndex() {

        $query = new Query();
        $data = $query->select('*')->from('menu')->where(['pid' => 0])->all();
        $secMenuData = [];
        foreach ($data as $key => $val) {
            $secMenuData[$key]['name'] = $val['name'];
            // 有二级菜单的时候 一级不需要链接 留空
            if (empty($val['url'])) {
                // 找二级菜单的信息
                $son = $query->select('*')->from('menu')->where(['pid' => $val['id']])->all();
                if (!empty($son)) {
                    foreach ($son as $k => $value) {
                        $secMenuData[$key]['sub_button'][] = [
                            'type' => 'view',
                            'url' => $value['content'],
                            'name' => $value['name'],
                        ];
                    }
                }
            } else {
                $secMenuData[$key]['type'] = 'view';
                $secMenuData[$key]['url'] = $val['url'];
            }
        }
//        print_R($secMenuData);exit;
        rsort($secMenuData);
        $secMenuData = ['button' => $secMenuData];
        $menuJson = json_encode($secMenuData, JSON_UNESCAPED_UNICODE);
        $token = Common::getToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $token;
        $data = Curl::_post($url, $menuJson);

        $data = json_decode($data, true);
        print_r($data);
        exit;

        return $this->render('index');
    }

    public function actionManage() {

        $token = Common::getToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . $token;

        $data = curl::_get($url);

        $data = json_decode($data, true);

        return $this->render('manage', ['button' => $data['menu']['button']]);
    }

    public function actionMenuadd() {

        $get = Yii::$app->request->get();

        foreach ($get['name'] as $key => $val) {

            if ($get['type'][$key] == 'parent') {

                $menu_child = array();
                foreach ($get['sub_name'][$key] as $k => $v) {

                    switch ($get['sub_type'][$key][$k]) {
                        case 'view':$type = 'url';
                            break;
                        case 'click':$type = 'key';
                            break;
                    }

                    $menu_child[] = array(
                        'name' => $v,
                        'type' => $get['sub_type'][$key][$k],
                        $type => $get['sub_val'][$key][$k]
                    );
                }

                $menu[] = array(
                    'name' => $val,
                    'sub_button' => $menu_child
                );
            } else {
                switch ($get['type'][$key]) {
                    case 'view':$type = 'url';
                        break;
                    case 'click':$type = 'key';
                        break;
                }

                $menu[] = array(
                    'name' => $val,
                    'type' => $get['type'][$key],
                    $type => $get['val'][$key]
                );
            }
        }
        $token = helper::getToken();

        $data['button'] = $menu;

        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $token;
        $data = curl::_post($url, $data);

        $data = json_decode($data, true);
        echo "2222";
        exit;
        if ($data['errmsg'] == 'ok') {
            $this->redirect('/menu/manage');
        }
    }

    private function _savetoken() {
//        echo strtotime("2017-1-1 2:1:2");exit;
        /* appID
          wx002d3c64259db853
          appsecret
          564baafdf2bfd30ba71d1dfb486bcc3b
         */
        if (!file_exists("token.txt")) {
            //{"access_token":"ACCESS_TOKEN","expires_in":7200}
            file_put_contents("token.txt", json_encode(['access_token' => '', 'expires_in' => 0, 'add_time' => 0]));
        }
        $token = file_get_contents("token.txt");
        $toke_data = json_decode($token, true);
        $expires_in = $toke_data['expires_in'];

        //过期了重新生成
//        echo '('.$toke_data['add_time'] .'+'. $expires_in.')' .'>='. time();exit;
        //16:02  + 7200
        if (empty($toke_data['add_time']) || (($toke_data['add_time'] + $expires_in) <= time())) {
            $appID = 'wx002d3c64259db853';
            $appsecret = '564baafdf2bfd30ba71d1dfb486bcc3b';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appID . "&secret={$appsecret}";
            $res = Curl::_get($url); //1.file_get_contents  2.地址url 3.curl  post/get
            //通过session 设置token有效时间：$_SESSION['token'] = "aaaa";
            //$res = json_decode($res, true);
            //print_r($res);exit;
            $de_res = json_decode($res, true);
            $de_res['add_time'] = time();
            file_put_contents("token.txt", json_encode($de_res));
        }
        //测试
        $toke_data = file_get_contents("token.txt");
        $toke_data = (json_decode($toke_data, true));
        return $toke_data['access_token'];
    }

}
